package com.study.demo.ui.userprofile;

import android.support.annotation.NonNull;

import com.stduy.injector.PerActivity;
import com.study.demo.api.game.GameApi;
import com.study.demo.bean.UserData;
import com.study.demo.bean.UserResult;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;


/**
 * Created by sll on 2016/3/11.
 */
@PerActivity
public class UserProfilePresenter implements UserProfileContract.Presenter {

    private GameApi mGameApi;
    private String uid;

    private Disposable disposable;
    private UserProfileContract.View mUserProfileView;

    @Inject
    public UserProfilePresenter(GameApi gameApi, String uid) {
        mGameApi = gameApi;
        this.uid = uid;
    }

    @Override
    public void receiveUserInfo() {
        mUserProfileView.showLoading();
        disposable = mGameApi.getUserInfo(uid)
                .map(this::convertToUserResult)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(userResult -> {
                            mUserProfileView.hideLoading();
                            if (userResult != null) {
                                mUserProfileView.renderUserData(userResult);
                            } else {
                                mUserProfileView.showError();
                            }
                        }, throwable -> {
                            mUserProfileView.hideLoading();
                            mUserProfileView.showError();
                        }
                );
    }

    private UserResult convertToUserResult(UserData userData) {
        if (userData != null) {
            return userData.result;
        }
        return null;
    }

    @Override
    public void attachView(@NonNull UserProfileContract.View view) {
        mUserProfileView = view;
    }

    @Override
    public void detachView() {
        if (disposable != null && !disposable.isDisposed()) {
            disposable.isDisposed();
        }
        mUserProfileView = null;
    }
}
